//
//  WDCacheStore.swift
//  WDDatabase
//
//  Created by Alean on 2023/1/5.
//

import UIKit
import UIKitExtentions

@objcMembers
public class WDCacheItem: NSObject {
    public var itemId: String?
    public var itemObject: Any?
    public var createdTime: Date?
    
    public init(itemId: String?, itemObject: Any?, createdTime: Date?) {
        self.itemId = itemId
        self.itemObject = itemObject
        self.createdTime = createdTime
    }
}

public let kTableName = "wd_cache"

public class WDCacheStore: NSObject {
    public override init() {
        super.init()
        WDDatabase.createDatabaseFile()
        let sql = "CREATE TABLE IF NOT EXISTS \(kTableName) (id TEXT NOT NULL, json TEXT NOT NULL, createdTime DATETIME NOT NULL, PRIMARY KEY(id))"
        WDDatabase.createTableQueue(tableName: kTableName, sql: sql)
    }

    /// 存储数据
    /// - Parameters:
    ///   - object: 非null object
    ///   - key: key
    @objc public func storeObject(_ object: Any, key: String) {
        let json = String.convert(fromJSON: object) ?? object
        let sql = "REPLACE INTO \(kTableName) (id, json, createdTime) values (?, ?, ?)"
        WDDatabase.insertQueue(tableName: kTableName, sql: sql, arguments: [key, json, Date()])
    }

    /// 读取数据
    /// - Parameter key: key
    /// - Returns: 非null的存储值
    @objc public func restoreObject(_ key: String) -> Any? {
        let item = restoreItem(key)
        return item?.itemObject
    }

    /// 读取数据详细信息
    /// - Parameter key: key
    /// - Returns: WDCacheItem 有object key 和时间
    @objc public func restoreItem(_ key: String) -> WDCacheItem? {
        let sql = "SELECT json, createdTime from \(kTableName) where id = ? Limit 1"
        var data: Any?
        WDDatabase.selectQueue(tableName: kTableName, sql: sql, arguments: [key]) { fs, datas in
            data = datas?.first
        }
        if let data = data as? [AnyHashable : Any],
           let json = data["json"] as? String,
           let createdTime = data["createdTime"] as? TimeInterval {
            let date = Date(timeIntervalSince1970: createdTime)
            let item = WDCacheItem(itemId: key, itemObject: json.toJsonObject(), createdTime: date)
            return item;
        }
        return nil
    }

    /// 删除某条数据
    /// - Parameter key: key
    @objc public func removeObject(_ key: String) {
        let sql = "DELETE from \(kTableName) where id = ?"
        WDDatabase.wdExecuteUpdateQueue(tableName: kTableName, sql: sql, arguments: [key])
    }

    /// 删除一组数据
    /// - Parameter keys: keys array
    @objc public func removeObjects(_ keys: [String]) {
        let stringArray = keys.map { " '\($0)' " }
        let string = stringArray.joined(separator: ",")
        let sql = "DELETE from \(kTableName) where id in ( \(string) )"
        WDDatabase.wdExecuteUpdateQueue(tableName: kTableName, sql: sql, arguments: [])
    }

    /// 删除缓存表
    @objc public func deleteCache() {
        WDDatabase.deleteDatabaseTableQueue(name: kTableName)
    }

    /// 清除表内内容
    @objc public func clearAllCache() {
        let sql = "DELETE from \(kTableName)"
        WDDatabase.wdExecuteUpdateQueue(tableName: kTableName, sql: sql, arguments: [])
    }
}
